<template>
    <div class="content" >
        <el-dialog :visible.sync="dataForm.dialogAddCount" :title="dataForm.title" size="tiny" :before-close="handleClose" v-loading="loading">
            <el-form ref="dataForm" :model="dataForm" :rules="rules" label-width="120px">
                <el-form-item label="倒计时开始日期" prop="startTime">
                    <el-date-picker :editable="false" :clearable="false"
                     v-model="dataForm.startTime" type="date" 
                     format="yyyy-MM-dd" placeholder="选择倒计时开始日期" 
                     :picker-options="ruleForm.pickerOptions1" 
                     @change="dateChange1" style="width:100%">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="倒计时结束日期" prop="endTime">
                    <el-date-picker :editable="false" :clearable="false"
                    v-model="dataForm.endTime" 
                    type="date" format="yyyy-MM-dd" 
                    placeholder="选择倒计时结束日期" 
                    :picker-options="ruleForm.pickerOptions2" 
                    @change="dateChange2" style="width:100%">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="倒计时内容" prop="content">
                    <el-row>
                        <el-col :span="3">距离</el-col>
                        <el-col :span="16">
                            <el-input v-model="dataForm.content" :maxlength="10" placeholder="请输入倒计时内容"></el-input>
                        </el-col>
                        <el-col :span="5" style="text-align:right">
                            还有{{dataForm.dateCount}}天
                        </el-col>
                    </el-row>
                </el-form-item>
               
                <el-row >
                    <div class="title-level" style="padding-left:36px">
                        <font color="red">*</font>&nbsp;
                        <span class="school-notice">显示班级</span>
                    </div>
                </el-row>
                <el-form-item>
                    <div class="classList-box">
                         <tree class="tree-box"
                            :getTreeList='dataForm.classList' 
                            :defaultExpanded='defaultExpanded'
                            @getIdList="getlistClassId"
                            :defaultChecked='dataForm.checkedListClassId'
                            >
                        </tree>
                    </div>
                </el-form-item>
            </el-form>
            <div class="footer">
                <el-button @click="cancel('dataForm')">取消</el-button>
                <el-button type="primary" @click="addDataForm('dataForm')">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import tree from 'components/tree';
import {getClassTree} from 'api/schoolNotice';
import {saveSchoolCountDown} from 'api/wisdom';
import { mapGetters } from 'vuex';
import moment from 'moment';
import validate from '@/utils/validate';
export default {
    name: 'addCountdown',
    components: { tree },
    props: {
        dataForm: {
            type: Object,
            required: true
        }
    },
    data() {
        return {
            loading: false,
            defaultExpanded: [], // 树默认展开的
            ruleForm: {
                pickerOptions1: {
                    disabledDate(time) {
                        return time.getTime() < new Date().getTime() - 864e5 ;
                    }
                },
                pickerOptions2: {
                    disabledDate(time) {
                        return time.getTime() < new Date().getTime() - 864e5;
                    }
                }
                // classList: [] // 树
            },
            rules: {
                startTime: [
                    {type: 'date', required: true, message: '请选择倒计时开始时间', trigger: 'blur'}
                ],
                endTime: [
                    {type: 'date', required: true, message: '请选择倒计时结束时间', trigger: 'blur'}
                ],
                content: [
                    {type: 'string', required: true, message: '请输入倒计时内容', trigger: 'blur'},
                    ...validate.validateText()
                ]
            }

        }
    },
    computed: {
        ...mapGetters([
            'schoolId'
        ])
    },
    watch: {
        'dataForm.dialogAddCount'(val) {
            if (val===true) {
                this.getTreeList();// 获取班级树
                this.dateCounFun();// 倒计时剩余天数的计算
            }
        }
    },
    methods: {
        // 获取班级树
        getTreeList() {
            getClassTree(this.schoolId).then(res => {
                this.defaultExpanded=[this.schoolId]// 默认全校班级是展开状态
                res.data.content.forEach((item, index) => {
                    let children=[];
                    item.classList.forEach((element) => {
                        children.push({
                            id: element.pId,
                            label: element.sNickName
                        })
                    })
                    if (item.gradeId) { // 有年级，就是普通学校 非培训机构 把班级 放在对应的年级下
                        this.dataForm.classList.push({
                            id: item.gradeId,
                            label: item.gradeName,
                            children
                        })
                    } else {// 直接把班级 放在全校下
                        this.dataForm.classList.push(children[0]);
                    }
                    
                })
                if (this.dataForm.classList.length) {
                    this.dataForm.classList=[{ 
                        id: this.schoolId,
                        label: '全校班级',
                        children: this.dataForm.classList
                    }]
                }
            })
        },
        // 勾选的班级时 获取id数组
        getlistClassId(data) {
            this.dataForm.checkedListClassId=data;
        },
        // 确定按钮
        addDataForm(ruleForm) {
            this.$refs[ruleForm].validate((valid) => {
                if (valid) {
                    if (!this.dataForm.checkedListClassId.length) {
                        this.$message.info('请选择显示班级！')
                        return
                    }
                    this.loading = true;
                    let json={
                        start: moment(this.dataForm.startTime).format('YYYY-MM-DD'),
                        end: moment(this.dataForm.endTime).format('YYYY-MM-DD'),
                        schoolId: this.schoolId,
                        content: this.dataForm.content,
                        list: [{classList: []}],
                        countDownId: this.dataForm.countDownId
                    }
                    this.dataForm.checkedListClassId.forEach((item) => {
                        json.list[0].classList.push({pId: item})
                    })
                    saveSchoolCountDown(json).then(res => {
                        this.loading = false;
                        this.$message.success('添加倒计时成功！');
                        this.$emit('search')
                        this.handleClose();
                    }).catch(() => {
                        this.loading = false;
                    })
                } else {
                    return false;
                }
            });
        },
        handleClose() {
            this.$refs.dataForm.resetFields();
            this.dataForm.dialogAddCount = false;
        },
        cancel() {
            this.dataForm.dialogAddCount = false;
        },
        //  功能：开始日期选择
        dateChange1(date) {
            this.dateCounFun();
            this.ruleForm.pickerOptions2 = {
                disabledDate(time) {
                    return time.getTime() < new Date(date).getTime() - 8.64e7 ;
                }
            };
        },

    // 功能：结束日期选择
        dateChange2(date) {
            this.dateCounFun();
            this.ruleForm.pickerOptions1 = {
                disabledDate(time) {// 开始时间
                    // 大于结束时间的 要禁用  小于今天的也要禁用
                    return time.getTime() > new Date(date).getTime() || new Date().getTime() - 864e5 > time.getTime();
                }
            };
        },
        // 计算倒计时天数
        dateCounFun() {
            if (this.dataForm.startTime&&this.dataForm.endTime) {
                let start=moment(this.dataForm.startTime).format('YYYY-MM-DD');
                let end=moment(this.dataForm.endTime).format('YYYY-MM-DD');
                let now=moment(new Date()).format('YYYY-MM-DD');
                let day='';
                if (end <= now) {// 结束时间<=今天
                    day = 0;
                } else {
                    let mend = moment(end);
                    let mnow = moment(now);
                    let mstart = moment(start);
                    /**
                     * 紧急处理，以后做优化
                     */
                    if (start < now) {// 开始时间<今天
                        // day = moment(mend - mnow).format('DD')-1;
                        day = (mend - mnow)/1000/60/60/24 -1;
                    } else {                // 开始时间>=今天
                        // day = moment(mend - mstart).format('DD')-1;
                        day = (mend - mstart)/1000/60/60/24 -1;
            
                    }
                }
                this.dataForm.dateCount=day;
            } else {
                this.dataForm.dateCount=0;
            }
        }
    }
}
</script>
<style lang="scss" scoped>
    .content{
        .classList-box{
            height: 300px;
            overflow: auto;
            border:1px solid #ebebeb;
        }
        .footer{
            text-align: center;
            margin-top: 40px;
        }
    }
</style>


